//
//  Persistencia.m
//  Pico y placa
//
//  Created by DmpmMacPro on 26/12/12.
//  Copyright (c) 2012 Mario Franco. All rights reserved.
//

#import "Persistencia.h"
#import "Tabla.h"
#import "Columna.h"

@implementation Persistencia
NSMutableArray * tablas;
int tablasCargando;


- (id)init
{
    self = [super init];
    if (self) {
        tablas = [[NSMutableArray alloc] init];
        tablasCargando = 0;
    }
    return self;
    
}


- (NSDictionary *) darVersionesDeArchivos
{
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/version.txt"];
    NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:path];
    
    return dict;
}

- (void) prueba
{
    for (Tabla * tabla in tablas)
    {
        NSLog(@"Tabla: %@", tabla.nombre);
        for (Columna * col in tabla.columnas)
        {
            NSLog(@"Columna: %@, entradas: %d", col.nombre, col.datos.count);
        }
    }
}

- (void) actualizarArchivoVersiones: (NSDictionary *) dict
{
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/version.txt"];
    [dict writeToFile:path atomically:YES];
    
    //    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.csv",nombreArchivo]];
}

- (void) cargarTablasPicoyPlaca
{
    [self vaciarTablas];
    tablasCargando += 3;
    
    //NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Horarios.csv"];
    NSString * pathHorarios = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Horarios.csv"];;
    //[self leerArchivo:[[NSBundle mainBundle] pathForResource:@"Horarios" ofType:@"csv"]];
    NSString * pathRestricciones = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Restricciones.csv"];;
    // [self leerArchivo:[[NSBundle mainBundle] pathForResource:@"Restricciones" ofType:@"csv"]];
    NSString * pathTipos = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Tipos_vehiculos.csv"];;
    // [self leerArchivo:[[NSBundle mainBundle] pathForResource:@"Tipos_vehiculos" ofType:@"csv"]];
    
    [NSThread detachNewThreadSelector:@selector(leerArchivo:) toTarget:self withObject:pathHorarios];
    [NSThread detachNewThreadSelector:@selector(leerArchivo:) toTarget:self withObject:pathRestricciones];
    [NSThread detachNewThreadSelector:@selector(leerArchivo:) toTarget:self withObject:pathTipos];
    
    
    while (tablasCargando != 0)
    {
        [NSThread sleepForTimeInterval:0.01];
    }
    //[self prueba];
}


- (void) leerArchivo: (NSString *) path
{
    NSString * extension = [path pathExtension];
    
    if([extension isEqualToString:@"csv"])
    {
        NSError * error;
        NSString * contenido = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
        
        [self leerTabla: contenido
              conTitulo:[[path lastPathComponent] stringByDeletingPathExtension]];
        
    }
    tablasCargando--;
    
}

- (void) vaciarTablas
{
    tablas = [[NSMutableArray alloc] init];
}


- (void) leerTabla: (NSString *) stringFile
         conTitulo: (NSString *) nom
{
    Tabla * nuevaTabla = [[Tabla alloc] init];
    nuevaTabla.nombre = nom;
    
    
    int numColumnas = 0;
    
    NSMutableArray * columnas = [[NSMutableArray alloc] init];
    
    NSString * file = [stringFile stringByReplacingOccurrencesOfString:@"," withString:@";"];
    file = [file stringByReplacingOccurrencesOfString:@"\n" withString:@"\r"];
    
    NSArray * lineas = [file componentsSeparatedByString: @"\r"];
    
    NSString * stringTitulos = [lineas objectAtIndex:0];
    
    
    NSArray * titulos = [stringTitulos componentsSeparatedByString:@";"];
    
    for (NSString * titulo in titulos)
    {
        if(![[titulo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""])
        {
            numColumnas++;
            
            Columna * nuevaCol = [[Columna alloc] init];
            
            nuevaCol.nombre = titulo;
            [columnas addObject:nuevaCol];
        }
    }
    
    BOOL primeraLinea = YES;
    for (NSString * linea in lineas)
    {
        if(primeraLinea)
        {
            primeraLinea = NO;
        }
        else if(![[[linea componentsSeparatedByString:@";"] objectAtIndex:0] isEqualToString:@""])
        {
            NSArray * valores = [linea componentsSeparatedByString:@";"];
            
            for (int i = 0; i < numColumnas; i++)
            {
                NSString * valor = [valores objectAtIndex:i];
                Columna * colActual = [columnas objectAtIndex:i];
                [colActual.datos addObject:valor];
            }
            
            
        }
        else
        {
            //NSLog(linea);
            
            //Si la linea esta vacia no se hace nada.
        }
    }
    
    nuevaTabla.columnas = columnas;
    
    [tablas addObject:nuevaTabla];
    
}

- (Tabla *) darTablaDeNombre: (NSString *) nombreTabla
{
    Tabla * retorno = nil;
    
    for(int i = 0; i < tablas.count && !retorno; i++)
    {
        Tabla * temp = [tablas objectAtIndex:i];
        if([temp.nombre isEqualToString:nombreTabla])
        {
            retorno = temp;
        }
    }
    
    return retorno;
}

- (NSMutableDictionary *) cargarTipoVehiculosFavoritos
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    
    NSError *error;
    
    NSString * filePath = [documentsDirectory stringByAppendingPathComponent:@"tipoVehiculos.txt"];
    
    NSString * file = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    
    if(file == nil)
    {
        return nil;
    }
    // NSLog(@"archivo %@ ", file);
    
    NSMutableArray * strings = [NSMutableArray arrayWithArray:[file componentsSeparatedByString:@"\n"]];
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    
    
    [dict setValue:[strings objectAtIndex:0] forKey:@"favorito"];
    
    [strings removeObjectAtIndex:0];
    
    [dict setValue:strings forKey:@"lista favoritos"];
    
    return dict;
    
    /*
     NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"AppFiles"]];
     NSString * filePath = [resourceDocPath stringByAppendingPathComponent:@"tipoVehiculos"];
     
     return [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
     */
    
}


- (void) guardarTipoVehiculoFav: (NSString *) favorito conListaFavoritos: (NSMutableArray *)favs
{
    
    /* NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"AppFiles/"]];
     NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"tipoVehiculos.txt"];
     */
    NSString * file = [NSString stringWithFormat:@"%@\n",favorito];
    
    
    for (NSString * fa in favs)
    {
        file = [file stringByAppendingFormat:@"%@\n",fa];
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    
    NSError *error;
    [file writeToFile:[documentsDirectory stringByAppendingPathComponent:@"tipoVehiculos.txt"]
           atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    /*
     
     NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
     
     [dict setValue:favorito forKey:@"favorito"];
     [dict setValue:favs forKey:@"lista favoritos"];
     NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"AppFiles"]];
     NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"tipoVehiculos"];
     
     NSLog(@"%d, %d",YES,[dict writeToFile:filePath atomically:YES]);
     */
    
}


/**
 * Revisa si existen los archivos por fuera del Bundle. Si no, los copia del Bundle.
 */
- (void) revisarExistenciaArchivos
{
    
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/version.txt"];
    
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
    
    if(!fileExists)
    {
        BOOL copioBien = YES;
        
        NSError* error = nil;
        NSString*  sourcePath =[[NSBundle mainBundle] pathForResource:@"version" ofType:@"txt"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path] && ![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:path error:&error]) {
            NSLog(@"Error copiando versiones. %@", error);
            copioBien = NO;
        }
        
        error = nil;
        path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Horarios.csv"];
        sourcePath =[[NSBundle mainBundle] pathForResource:@"Horarios" ofType:@"csv"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path] && ![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:path error:&error]) {
            NSLog(@"Error copiando horarios. %@", error);
            copioBien = NO;
        }
        
        error = nil;
        path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Restricciones.csv"];
        sourcePath =[[NSBundle mainBundle] pathForResource:@"Restricciones" ofType:@"csv"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path] && ![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:path error:&error]) {
            NSLog(@"Error copiando restricciones. %@", error);
            copioBien = NO;
        }
        
        error = nil;
        path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Tipos_vehiculos.csv"];
        sourcePath =[[NSBundle mainBundle] pathForResource:@"Tipos_vehiculos" ofType:@"csv"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:path] && ![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:path error:&error]) {
            NSLog(@"Error copiando tipos vehiculos. %@", error);
            copioBien = NO;
        }
        
        if(!copioBien)
        {
            NSLog(@"Error copiando alguno de los archivos");
        }
        else
        {
            NSLog(@"Copió exitosamente los archivos");
        }
    }
    
}

@end
